<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 7.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.ico">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" integrity="sha256-wiz7ZSCn/btzhjKDQBms9Hx4sSeUYsDrTLg7roPstac=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.28/fancybox/fancybox.css" integrity="sha256-6cQIC71/iBIYXFK+0RHAvwmjwWzkWd+r7v/BX3/vZDc=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/themes/green/pace-theme-minimal.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/pace.min.js" integrity="sha256-gqd7YTjg/BtfqWSwsJOvndl0Bxc8gFImLEkXQT8+qj0=" crossorigin="anonymous"></script>

<script class="next-config" data-name="main" type="application/json">{"hostname":"sumumm.github.io","root":"/","images":"/images","scheme":"Gemini","darkmode":false,"version":"8.19.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":"mac"},"fold":{"enable":true,"height":300},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":true,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="本文主要是用C语言获取Linux系统时间的相关笔记，若笔记中有错误或者不合适的地方，欢迎批评指正😃。">
<meta property="og:type" content="article">
<meta property="og:title" content="LV05-07-Linux系统-02-系统时间">
<meta property="og:url" content="https://sumumm.github.io/post/2bc2262c.html">
<meta property="og:site_name" content="苏木">
<meta property="og:description" content="本文主要是用C语言获取Linux系统时间的相关笔记，若笔记中有错误或者不合适的地方，欢迎批评指正😃。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/LV05-07-Linux%E7%B3%BB%E7%BB%9F-02-%E7%B3%BB%E7%BB%9F%E6%97%B6%E9%97%B4/img/image-20220621064820204.png">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/LV05-07-Linux%E7%B3%BB%E7%BB%9F-02-%E7%B3%BB%E7%BB%9F%E6%97%B6%E9%97%B4/img/image-20220621071320066.png">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/LV05-07-Linux%E7%B3%BB%E7%BB%9F-02-%E7%B3%BB%E7%BB%9F%E6%97%B6%E9%97%B4/img/image-20220621071518745.png">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/LV05-07-Linux%E7%B3%BB%E7%BB%9F-02-%E7%B3%BB%E7%BB%9F%E6%97%B6%E9%97%B4/img/image-20220621120417357.png">
<meta property="article:published_time" content="2023-07-02T13:52:37.000Z">
<meta property="article:modified_time" content="2025-06-13T16:25:56.996Z">
<meta property="article:author" content="苏木">
<meta property="article:tag" content="LV05-操作系统">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/LV05-07-Linux%E7%B3%BB%E7%BB%9F-02-%E7%B3%BB%E7%BB%9F%E6%97%B6%E9%97%B4/img/image-20220621064820204.png">


<link rel="canonical" href="https://sumumm.github.io/post/2bc2262c.html">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://sumumm.github.io/post/2bc2262c.html","path":"post/2bc2262c.html","title":"LV05-07-Linux系统-02-系统时间"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>LV05-07-Linux系统-02-系统时间 | 苏木</title>
  








    <script src="/js/browser_tools_disable.js"></script>

  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
<!-- hexo injector head_end start --><link rel="stylesheet" href="https://unpkg.com/hexo-next-tags-plus@latest/lib/tag_plus.css" media="defer" onload="this.media='all'"><!-- hexo injector head_end end --></head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">苏木</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">我的学习之路</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>苏木的家</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类页<span class="badge">42</span></a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档页<span class="badge">673</span></a></li><li class="menu-item menu-item-flink"><a href="/flink/" rel="section"><i class="fa fa-link fa-fw"></i>友人帐</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于我</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%80%E3%80%81%E6%97%A5%E6%9C%9F%E4%B8%8E%E6%97%B6%E9%97%B4"><span class="nav-text">一、日期与时间</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E6%97%B6%E9%97%B4%E7%9A%84%E5%9F%BA%E6%9C%AC%E6%A6%82%E5%BF%B5"><span class="nav-text">1. 时间的基本概念</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-%E6%97%B6%E5%8C%BA"><span class="nav-text">1.1 时区</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2-GMT-%E6%97%B6%E9%97%B4"><span class="nav-text">1.2 GMT 时间</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-3-UTC-%E6%97%B6%E9%97%B4"><span class="nav-text">1.3 UTC 时间</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-4-CST-%E6%97%B6%E9%97%B4"><span class="nav-text">1.4 CST 时间</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-Ubuntu-%E4%B8%AD%E7%9A%84%E6%97%B6%E9%97%B4"><span class="nav-text">2. Ubuntu 中的时间</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-%E7%9B%B8%E5%85%B3%E5%91%BD%E4%BB%A4"><span class="nav-text">2.1 相关命令</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-%E6%97%B6%E5%8C%BA%E4%BF%A1%E6%81%AF%E6%96%87%E4%BB%B6"><span class="nav-text">2.2 时区信息文件</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-Linux-%E7%B3%BB%E7%BB%9F%E4%B8%AD%E7%9A%84%E6%97%B6%E9%97%B4"><span class="nav-text">3. Linux 系统中的时间</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-%E5%AE%9E%E6%97%B6%E6%97%B6%E9%92%9FRTC"><span class="nav-text">3.1 实时时钟RTC</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-Linux-%E5%A6%82%E4%BD%95%E8%AE%B0%E5%BD%95%E6%97%B6%E9%97%B4"><span class="nav-text">3.2 Linux 如何记录时间</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-3-jiffies"><span class="nav-text">3.3 jiffies </span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-4-%E6%97%A5%E5%8E%86%E6%97%B6%E9%97%B4"><span class="nav-text">3.4 日历时间</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-%E8%8E%B7%E5%8F%96%E6%97%B6%E9%97%B4"><span class="nav-text">4. 获取时间</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-1-time-%E5%87%BD%E6%95%B0"><span class="nav-text">4.1 time() 函数</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#4-1-1-%E5%87%BD%E6%95%B0%E8%AF%B4%E6%98%8E"><span class="nav-text">4.1.1 函数说明</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-1-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B"><span class="nav-text">4.1.2 使用实例</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-2-gettimeofday-%E5%87%BD%E6%95%B0"><span class="nav-text">4.2 gettimeofday() 函数</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#4-2-1-%E5%87%BD%E6%95%B0%E8%AF%B4%E6%98%8E"><span class="nav-text">4.2.1 函数说明</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-2-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B"><span class="nav-text">4.2.2 使用实例</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-%E6%97%B6%E9%97%B4%E8%BD%AC%E6%8D%A2"><span class="nav-text">5. 时间转换</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#5-1-ctime-%E5%87%BD%E6%95%B0"><span class="nav-text">5.1 ctime() 函数</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#5-1-1-%E5%87%BD%E6%95%B0%E8%AF%B4%E6%98%8E"><span class="nav-text">5.1.1 函数说明</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-1-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B"><span class="nav-text">5.1.2 使用实例</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-2-localtime-%E5%87%BD%E6%95%B0"><span class="nav-text">5.2 localtime() 函数</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#5-2-1-%E5%87%BD%E6%95%B0%E8%AF%B4%E6%98%8E"><span class="nav-text">5.2.1 函数说明</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-2-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B"><span class="nav-text">5.2.2 使用实例</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-%E6%97%B6%E9%97%B4%E7%9B%B8%E5%85%B3API%E6%80%BB%E7%BB%93"><span class="nav-text">6. 时间相关API总结</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%89%E3%80%81%E8%BF%9B%E7%A8%8B%E6%97%B6%E9%97%B4"><span class="nav-text">三、进程时间</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E4%BB%80%E4%B9%88%E6%98%AF%E8%BF%9B%E7%A8%8B%E6%97%B6%E9%97%B4"><span class="nav-text">1. 什么是进程时间</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-times-%E5%87%BD%E6%95%B0"><span class="nav-text">2. times() 函数</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-%E5%87%BD%E6%95%B0%E8%AF%B4%E6%98%8E"><span class="nav-text">2.1 函数说明</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B"><span class="nav-text">2.2 使用实例</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-clock-%E5%87%BD%E6%95%B0"><span class="nav-text">3. clock() 函数</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-%E5%87%BD%E6%95%B0%E8%AF%B4%E6%98%8E"><span class="nav-text">3.1 函数说明</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B"><span class="nav-text">3.2 使用实例</span></a></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="苏木"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">苏木</p>
  <div class="site-description" itemprop="description">莫道桑榆晚，为霞尚满天</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">673</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">42</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">43</span>
        <span class="site-state-item-name">标签</span>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/sumumm" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;sumumm" rel="noopener me" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://sumumm.github.io/post/2bc2262c.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="苏木">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="苏木">
      <meta itemprop="description" content="莫道桑榆晚，为霞尚满天">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="LV05-07-Linux系统-02-系统时间 | 苏木">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          LV05-07-Linux系统-02-系统时间
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2023-07-02 21:52:37" itemprop="dateCreated datePublished" datetime="2023-07-02T21:52:37+08:00">2023-07-02</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/" itemprop="url" rel="index"><span itemprop="name">嵌入式开发</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/" itemprop="url" rel="index"><span itemprop="name">01HQ课程体系</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/" itemprop="url" rel="index"><span itemprop="name">LV05-操作系统</span></a>
        </span>
    </span>

  
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>7.6k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>28 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><p>本文主要是用C语言获取Linux系统时间的相关笔记，若笔记中有错误或者不合适的地方，欢迎批评指正😃。</p>
<span id="more"></span>

<!-- Photo: https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/LV05-07-Linux%E7%B3%BB%E7%BB%9F-02-%E7%B3%BB%E7%BB%9F%E6%97%B6%E9%97%B4/img/ -->

<details class="folding-tag" blue><summary> 点击查看使用工具及版本 </summary>
              <div class='content'>
              <table>    <tr>        <td align="center" width=150px>Windows</td>        <td align="left">windows11</td>    </tr>    <tr>        <td align="center">Ubuntu</td>        <td align="left">Ubuntu16.04的64位版本</td>      </tr>    <tr>        <td align="center">VMware® Workstation 16 Pro</td>        <td align="left">16.2.3 build-19376536</td>      </tr>    <tr>        <td align="center">SecureCRT</td>        <td align="left">Version 8.7.2 (x64 build 2214)   -   正式版-2020年5月14日</td>      </tr>    <tr>        <td align="center">开发板</td>        <td align="left">正点原子 i.MX6ULL Linux阿尔法开发板</td>      </tr>    <tr>        <td align="center">uboot</td>        <td align="left">NXP官方提供的uboot，NXP提供的版本为uboot-imx-rel_imx_4.1.15_2.1.0_ga(使用的uboot版本为U-Boot 2016.03)</td>      </tr>    <tr>        <td align="center">linux内核</td>        <td align="left">linux-4.15(NXP官方提供)</td>      </tr>    <tr>        <td align="center">STM32开发板</td>        <td align="left">正点原子战舰V3(STM32F103ZET6)</td>      </tr></table>
              </div>
            </details>

<details class="folding-tag" blue><summary> 点击查看本文参考资料 </summary>
              <div class='content'>
              <table>    <tr><td align="center">参考方向  </td><td align="center">参考原文</td></tr>    <tr><td align="left">---</td><td align="left"><a href="" target="_blank">--- <i class="fa fa-external-link-alt"></i> </a></td></tr></table>
              </div>
            </details>

<details class="folding-tag" blue><summary> 点击查看相关文件下载 </summary>
              <div class='content'>
              <table>    <tr>        <td align="center">---</td>        <td align="left">--- <a href="" target="_blank">  <i class="fa fa-external-link-alt"></i></a></td>      </tr></table>
              </div>
            </details>

<h1 id="一、日期与时间"><a href="#一、日期与时间" class="headerlink" title="一、日期与时间"></a><font size=3>一、日期与时间</font></h1><h2 id="1-时间的基本概念"><a href="#1-时间的基本概念" class="headerlink" title="1. 时间的基本概念"></a><font size=3>1. 时间的基本概念</font></h2><h3 id="1-1-时区"><a href="#1-1-时区" class="headerlink" title="1.1 时区"></a><font size=3>1.1 时区</font></h3><p>地球是自西向东自转，东边比西边先看到太阳，东边的时间也比西边的早。东边时刻与西边时刻的差值不仅要以时计，而且还要以分和秒来计算，这给人们带来不便。<br>为了克服时间上的混乱，<code>1884</code>年在华盛顿召开的一次国际经度会议（又称国际子午线会议）上，规定将全球划分为<code>24</code>个时区（东、西各<code>12</code>个时区）。</p>
<p>以格林尼治天文台旧址的本初子午线作为零度经线，将全球划分为东西两个半球，<code>24</code>个时区就为东<code>1—12</code>区，西<code>1—12</code>区。每个时区横跨经度<code>15</code>度，时间正好是<code>1</code>小时。最后的东、西第<code>12</code>区其实是一个时区，就是<code>12</code>区，它们各跨经度<code>7.5</code>度，以东、西经<code>180</code>度为界。而本初子午线所在时区被称为<strong>中时区</strong>（零时区）。</p>
<img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/LV05-07-Linux%E7%B3%BB%E7%BB%9F-02-%E7%B3%BB%E7%BB%9F%E6%97%B6%E9%97%B4/img/image-20220621064820204.png" alt="image-20220621064820204" style="zoom: 80%;" />

<p>每个时区的中央经线上的时间就是这个时区内统一采用的时间，称为<strong>区时</strong>。相邻两个时区的时间相差<code>1</code>小时。例如，我国东<code>8</code>区的时间总比泰国东<code>7</code>区的时间早<code>1</code>小时，而比日本东<code>9</code>区的时间晚1小时。因此，出国旅行的人，必须随时调整自己的手表，才能和当地时间相一致。凡向西走，每过一个时区，就要把表向前拨<code>1</code>小时(比如<code>2</code>点拨到<code>1</code>点)；凡向东走，每过一个时区，就要把表向后拨<code>1</code>小时（比如<code>1</code>点拨到<code>2</code>点）。<br>实际上，世界上不少国家和地区都不严格按时区来计算时间。为了在全国范围内采用统一的时间，一般都把某一个时区的时间作为全国统一采用的时间。例如，我国把首都北京所在的东<code>8</code>区的时间作为全国统一的时间，称为北京时间，北京时间就作为我国使用的本地时间，我们电脑上显示的时间就是北京时间，我国国土面积广大，由东到西横跨了<code>5</code>个时区，也就意味着我国最东边的地区与最西边的地区实际上相差了<code>4</code>、<code>5</code>个小时。又例如，英国、法国、荷兰和比利时等国，虽地处中时区，但为了和欧洲大多数国家时间相一致，则采用东<code>1</code>区的时间。</p>
<h3 id="1-2-GMT-时间"><a href="#1-2-GMT-时间" class="headerlink" title="1.2 GMT 时间"></a><font size=3>1.2 GMT 时间</font></h3><p><code>GMT</code>（<code>Greenwich Mean Time</code>）中文全称是格林尼治标准时间，这个时间系统的概念在<code>1884</code>年被确立，由英国伦敦的格林威治皇家天文台计算并维护，并在之后的几十年向欧陆其它国家扩散。<br>由于从<code>19</code>世纪开始，因为世界各国往来频繁，而欧洲大陆、美洲大陆以及亚洲大陆都有各自的时区，所以为了避免时间混乱，<code>1884</code>年，各国代表在美国华盛顿召开国际大会，通过协议选出英国伦敦的格林威治作为全球时间的中心点，决定以通过格林尼治的子午线作为划分东西两半球的经线零度线（本初子午线、零度经线），由此格林威治标准时间因而诞生。<br><code>GMT</code>时间就是英国格林威治当地时间，也就是零时区（中时区）所在时间，例如<code>GMT 12:00</code>就是指英国伦敦的格林威治皇家天文台当地的中午<code>12:00</code>，与我国的标准时间北京时间（东<code>8</code>区）相差<code>8</code>个小时，即早<code>8</code>个小时，所以<code>GMT 12:00</code>对应的北京时间是<code>20:00</code>。</p>
<h3 id="1-3-UTC-时间"><a href="#1-3-UTC-时间" class="headerlink" title="1.3 UTC 时间"></a><font size=3>1.3 UTC 时间</font></h3><p><code>UTC</code>（<code>Coordinated Universal Time</code>）指的是世界协调时间（又称世界标准时间、世界统一时间），是经过平均太阳时(以格林尼治时间<code>GMT</code>为准)、地轴运动修正后的新时标以及以秒为单位的国际原子时所综合精算而成的时间，计算过程相当严谨精密，因此若以世界标准时间的角度来说，<code>UTC</code>比<code>GMT</code>更加精准。</p>
<p><code>GMT</code>与<code>UTC</code>这两者几乎是同一概念，它们都是指格林威治标准时间，也就是国际标准时间，只不过<code>UTC</code>时间比<code>GMT</code>时间更加精准。</p>
<h3 id="1-4-CST-时间"><a href="#1-4-CST-时间" class="headerlink" title="1.4 CST 时间"></a><font size=3>1.4 CST 时间</font></h3><p>在<code>Ubuntu</code>中，我们还可能会看到<code>CST</code>时间，这又是什么呢？<code>CST</code>可视为美国、澳大利亚、古巴或中国的标准时间。<code>CST</code>可以为如下<code>4</code>个不同的时区的缩写：</p>
<ul>
<li><p>美国中部时间：<code>Central Standard Time （USA） UT-6:00</code></p>
</li>
<li><p>澳大利亚中部时间：<code>Central Standard Time （Australia） UT+9:30</code></p>
</li>
<li><p>中国标准时间：<code>China Standard Time UT+8:00</code></p>
</li>
<li><p>古巴标准时间：<code>Cuba Standard Time UT-4:00</code></p>
</li>
</ul>
<h2 id="2-Ubuntu-中的时间"><a href="#2-Ubuntu-中的时间" class="headerlink" title="2. Ubuntu 中的时间"></a><font size=3>2. Ubuntu 中的时间</font></h2><h3 id="2-1-相关命令"><a href="#2-1-相关命令" class="headerlink" title="2.1 相关命令"></a><font size=3>2.1 相关命令</font></h3><p>在<code>Ubuntu</code>中，我们可以通过<code>date</code>命令来查看系统当前的本地时间，我们在终端输入以下命令：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">date</span><br></pre></td></tr></table></figure>

<p>然后便会出现以下信息：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">2022年 06月 21日 星期二 07:07:53 CST</span><br></pre></td></tr></table></figure>

<p><code>CST</code>在这里其实指的是<code>China Standard Time</code>（中国标准时间）的缩写，表示当前查看到的时间是中国标准时间，也就是我国所使用的标准时间——北京时间，一般在安装<code>Ubuntu</code>系统的时候会提示我们设置所在城市，那么系统便会根据我们所设置的城市来确定系统的本地时间对应的时区，就像我设置的城市为上海，那么系统的本地时间就是北京时间，这是因为我国统一使用北京时间作为本国的标准时间。<br>我们在终端输入以下命令：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">date -u</span><br></pre></td></tr></table></figure>

<p>然后便会看到输出的时间信息如下：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">2022年 06月 20日 星期一 23:07:49 UTC</span><br></pre></td></tr></table></figure>

<p>这样显示的就是<code>UTC</code>时间了，可以看到与上边的<code>CST</code>时间相差了<code>8</code>小时。</p>
<h3 id="2-2-时区信息文件"><a href="#2-2-时区信息文件" class="headerlink" title="2.2 时区信息文件"></a><font size=3>2.2 时区信息文件</font></h3><p>在<code>Ubuntu</code>系统，时区信息通常以标准格式保存在一些文件当中，这些文件通常位于<code>/usr/share/zoneinfo</code>目录下，该目录下的每一个文件（包括子目录下的文件）都包含了一个特定国家或地区内时区制度的相关信息，且往往根据其所描述的城市或地区缩写来加以命名，例如，<code>EST</code>（美国东部标准时间）、<code>CET</code>（欧洲中部时间）、<code>UTC</code>（世界标准时间）、<code>Hongkong</code>、等，也把这些文件称为时区配置文件，我们可以通过以下命令查看相关文件名称：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ls /usr/share/zoneinfo</span><br></pre></td></tr></table></figure>

<p>然后便会看到以下信息输出：</p>
<img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/LV05-07-Linux%E7%B3%BB%E7%BB%9F-02-%E7%B3%BB%E7%BB%9F%E6%97%B6%E9%97%B4/img/image-20220621071320066.png" alt="image-20220621071320066" style="zoom:50%;" />

<p>系统的本地时间由时区配置文件<code>/etc/localtime</code>定义，通常链接到<code>/usr/share/zoneinfo</code>目录下的某一个文件（或其子目录下的某一个文件），我们可以查看一下这个文件：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ls -l /etc/localtime</span><br></pre></td></tr></table></figure>

<p>然后便会看到以下信息：</p>
<img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/LV05-07-Linux%E7%B3%BB%E7%BB%9F-02-%E7%B3%BB%E7%BB%9F%E6%97%B6%E9%97%B4/img/image-20220621071518745.png" alt="image-20220621071518745" style="zoom: 80%;" />

<p>这样的话，如果我们要修改<code>Ubuntu</code>系统本地时间的时区信息，可以直接将<code>/etc/localtime</code>链接到<code>/usr/share/zoneinfo</code>目录下的任意一个时区配置文件:</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">sudo rm -rf localtime                        # 删除原有链接文件 </span><br><span class="line">sudo ln -s /usr/share/zoneinfo/EST localtime # 重新建立链接文件</span><br></pre></td></tr></table></figure>

<h2 id="3-Linux-系统中的时间"><a href="#3-Linux-系统中的时间" class="headerlink" title="3. Linux 系统中的时间"></a><font size=3>3. Linux 系统中的时间</font></h2><h3 id="3-1-实时时钟RTC"><a href="#3-1-实时时钟RTC" class="headerlink" title="3.1 实时时钟RTC"></a><font size=3>3.1 实时时钟<code>RTC</code></font></h3><p>操作系统中一般会有两个时钟，一个系统时钟（<code>system clock</code>），一个实时时钟（<code>Real time clock</code>），也叫<code>RTC</code>。系统时钟由系统启动之后由内核来维护，例如，使用<code>date</code>命令查看到的就是系统时钟，它在系统关机情况下是不存在的；而实时时钟一般由<code>RTC</code>时钟芯片提供，<code>RTC</code>芯片有相应的电池供电，以保证系统在关机情况下<code>RTC</code>能够继续工作、继续计时。</p>
<h3 id="3-2-Linux-如何记录时间"><a href="#3-2-Linux-如何记录时间" class="headerlink" title="3.2 Linux 如何记录时间"></a><font size=3>3.2 Linux 如何记录时间</font></h3><p><code>Linux</code>系统在开机启动之后首先会读取<code>RTC</code>硬件获取实时时钟作为系统时钟的初始值，之后内核便开始维护自己的系统时钟。所以，<code>RTC</code>硬件只有在系统开机启动时会读取一次，目的是用于对系统时钟进行初始化操作，之后的运行过程中便不会再对其进行读取操作了。而在系统关机时，内核会将系统时钟写入到<code>RTC</code>硬件。</p>
<h3 id="3-3-jiffies"><a href="#3-3-jiffies" class="headerlink" title="3.3 jiffies "></a><font size=3>3.3 jiffies </font></h3><p><code>jiffies</code>是内核中定义的一个全局变量，内核使用<code>jiffies</code>来记录系统从启动以来的系统节拍数，所以这个变量用来记录以系统节拍时间为单位的时间长度。</p>
<p><code>Linux</code>内核在编译配置时定义了一个节拍时间，使用<strong>节拍率</strong>（一秒钟多少个节拍数）来表示，例如如常用的节拍率为<code>100Hz</code>（<code>1</code>秒钟<code>100</code>个节拍数，节拍时间为<code>1s / 100</code>）、<code>200Hz</code>（<code>1</code>秒钟<code>200</code>个节拍，节拍时间为<code>1s / 200</code>）、<code>250Hz</code>（<code>1</code>秒钟<code>250</code>个节拍，节拍时间为<code>1s / 250</code>）、<code>300Hz</code>（<code>1</code>秒钟<code>300</code>个节拍，节拍时间为<code>1s / 300</code>）、<code>500Hz</code>（<code>1</code>秒钟<code>500</code>个节拍，节拍时间为<code>1s / 500</code>）等。由此可以发现配置的节拍率越低，每一个系统节拍的时间就越短，也就意味着<code>jiffies</code>记录的时间精度越高，当然，高节拍率会导致系统中断的产生更加频繁，频繁的中断会加剧系统的负担，一般默认情况下都是采用<code>100Hz</code>作为系统节拍率。</p>
<p>内核其实是通过<code>jiffies</code>来维护系统时钟，全局变量<code>jiffies</code>在系统开机启动时会设置一个初始值，<code>RTC</code>实时时钟会在系统开机启动时读取一次，目的是用于对系统时钟进行初始化，这里说的初始化其实指的就是对内核的<code>jiffies</code>变量进行初始化操作，具体如何将读取到的实时时钟换算成<code>jiffies</code>数值，后边用到了再说吧。</p>
<p>操作系统使用<code>jiffies</code>这个全局变量来记录当前时间，当我们需要获取到系统当前时间点时，就可以使用<code>jiffies</code>变量去计算，当然并不需要我们手动去计算，<code>Linux</code>系统提供了相应的系统调用或<code>C</code>库函数用于获取当前时间，例如如系统调用<code>time()</code>、<code>gettimeofday()</code>，其实质上就是通过<code>jiffies</code>变量换算得到。</p>
<p>【说明】系统的节拍率可以使用下边的函数获取：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">sysconf(_SC_CLK_TCK);</span><br></pre></td></tr></table></figure>



<h3 id="3-4-日历时间"><a href="#3-4-日历时间" class="headerlink" title="3.4 日历时间"></a><font size=3>3.4 日历时间</font></h3><p>自<code>1970-01-01 00:00:00 +0000 (UTC)</code>以来经过的总秒数，我们把这个称之为<strong>日历时间</strong>或<code>time_t</code>时间。为什么是<code>1970-01-01</code>开始嘛，可以上网搜一下，这里就不写了。</p>
<h2 id="4-获取时间"><a href="#4-获取时间" class="headerlink" title="4. 获取时间"></a><font size=3>4. 获取时间</font></h2><h3 id="4-1-time-函数"><a href="#4-1-time-函数" class="headerlink" title="4.1 time() 函数"></a><font size=3>4.1 time() 函数</font></h3><h4 id="4-1-1-函数说明"><a href="#4-1-1-函数说明" class="headerlink" title="4.1.1 函数说明"></a><font size=3>4.1.1 函数说明</font></h4><p>在<code>linux</code>下可以使用<code>man 2 time</code>命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;time.h&gt;</span></span></span><br><span class="line">    </span><br><span class="line"><span class="comment">/* 函数声明 */</span></span><br><span class="line"><span class="type">time_t</span> <span class="title function_">time</span><span class="params">(<span class="type">time_t</span> *tloc)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数用于获取当前时间，以秒为单位。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li><code>tloc</code>：<code>time_t</code>类型指针变量，如果<code>tloc</code>参数不是<code>NULL</code>，则返回值也存储在<code>tloc</code>指向的内存中。</li>
</ul>
<p><strong>【返回值】</strong><code>time_t</code>类型，成功则返回自<code>1970-01-01 00:00:00 +0000 (UTC)</code>以来的时间值（以秒为单位）；失败则返回<code>-1</code>，并会设置<code>errno</code>表示错误类型。</p>
<p><strong>【使用格式】</strong>一般情况下基本使用格式如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需要包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;time.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 至少应该有的语句 */</span></span><br><span class="line"><span class="type">time_t</span> nowTime;</span><br><span class="line">nowTime = time(<span class="literal">NULL</span>);</span><br></pre></td></tr></table></figure>

<p><strong>【注意事项】</strong></p>
<p>（1）<code>time</code>函数获取得到的是一个时间段，也就是从<code>1970-01-01 00:00:00 +0000 (UTC)</code>到现在这段时间所经过的秒数，所以我们要计算现在这个时间点，只需要使用<code>time()</code>得到的秒数加<code>1970-01-01 00:00:00</code>即可。</p>
<p>（2）我们要是想打印出这个总的秒数，使用<code>printf</code>的时候，格式字符需要使用<code>%ld</code>。</p>
<h4 id="4-1-2-使用实例"><a href="#4-1-2-使用实例" class="headerlink" title="4.1.2 使用实例"></a><font size=3>4.1.2 使用实例</font></h4><details class="folding-tag" blue><summary> 点击查看实例 </summary>
              <div class='content'>
              <figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;time.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> arc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="type">time_t</span> nowTime;</span><br><span class="line">	nowTime = time(<span class="literal">NULL</span>);</span><br><span class="line">	<span class="keyword">if</span> (nowTime == <span class="number">-1</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		perror(<span class="string">&quot;time error&quot;</span>);</span><br><span class="line">		<span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;nowTime: %ld\n&quot;</span>, nowTime);</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令编译程序：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall # 生成可执行文件 a.out </span><br><span class="line">./a.out # 执行可执行程序</span><br></pre></td></tr></table></figure><p>然后，终端会有以下信息显示：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">nowTime: 1655778106</span><br></pre></td></tr></table></figure>
              </div>
            </details>

<h3 id="4-2-gettimeofday-函数"><a href="#4-2-gettimeofday-函数" class="headerlink" title="4.2 gettimeofday() 函数"></a><font size=3>4.2 gettimeofday() 函数</font></h3><h4 id="4-2-1-函数说明"><a href="#4-2-1-函数说明" class="headerlink" title="4.2.1 函数说明"></a><font size=3>4.2.1 函数说明</font></h4><p>在<code>linux</code>下可以使用<code>man 2 gettimeofday</code>命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/time.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 函数声明 */</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">gettimeofday</span><span class="params">(<span class="keyword">struct</span> timeval *tv, <span class="keyword">struct</span> timezone *tz)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数用于获取当前时间，以微秒为单位。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li><code>tv</code>：<code>struct timeval</code>类型的结构体指针变量，获取得到的时间值存储在该所指向的<code>struct timeval</code>结构体变量中，该结构体包含了两个成员变量<code>tv_sec</code>和<code>tv_usec</code>，分别用于表示秒和微秒，所以获取得到的时间值就是<code>tv_sec</code>（秒）<code>+</code>  <code>tv_usec</code>（微秒），同样获取得到的秒数与<code>time()</code>函数一样，也是自<code>1970-01-01 00:00:00 +0000 (UTC)</code>到现在这段时间所经过的秒数，也就是日历时间，<code>time()</code>返回得到的值和函数<code>gettimeofday()</code>所返回的<code>tv</code>参数中<code>tv_sec</code>字段的数值相同。</li>
</ul>
<details class="folding-tag" blue><summary> 点击查看 struct timeval 结构体成员 </summary>
              <div class='content'>
              <p>在使用<code>man</code>手册的时候会有说明：</p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">timeval</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">	<span class="type">time_t</span>      tv_sec;     <span class="comment">/* seconds 秒*/</span></span><br><span class="line">	<span class="type">suseconds_t</span> tv_usec;    <span class="comment">/* microseconds 微秒*/</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
              </div>
            </details>

<ul>
<li><code>tz</code>：<code>struct timezone</code>类型结构体指针变量，早期实现用其来获取系统的时区信息，目前已遭废弃，在调用<code>gettimeofday()</code>函数时应将参数<code>tz</code>设置为<code>NULL</code>。</li>
</ul>
<details class="folding-tag" blue><summary> 点击查看 struct timeval 结构体成员 </summary>
              <div class='content'>
              <p>在使用<code>man</code>手册的时候会有说明：</p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">timezone</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">	<span class="type">int</span> tz_minuteswest;     <span class="comment">/* minutes west of Greenwich */</span></span><br><span class="line">	<span class="type">int</span> tz_dsttime;         <span class="comment">/* type of DST correction */</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
              </div>
            </details>

<p><strong>【返回值】</strong><code>time_t</code>类型，成功则返回自<code>0</code>；失败则返回<code>-1</code>，并会设置<code>errno</code>表示错误类型。</p>
<p><strong>【使用格式】</strong>一般情况下基本使用格式如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需要包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/time.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 至少应该有的语句 */</span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">timeval</span> <span class="title">tval</span>;</span></span><br><span class="line">gettimeofday(&amp;tval, <span class="literal">NULL</span>);</span><br></pre></td></tr></table></figure>

<p><strong>【注意事项】</strong><code>none</code></p>
<h4 id="4-2-2-使用实例"><a href="#4-2-2-使用实例" class="headerlink" title="4.2.2 使用实例"></a><font size=3>4.2.2 使用实例</font></h4><details class="folding-tag" blue><summary> 点击查看实例 </summary>
              <div class='content'>
              <figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/time.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> arc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="type">int</span> ret;</span><br><span class="line">	<span class="class"><span class="keyword">struct</span> <span class="title">timeval</span> <span class="title">nowTime</span>;</span></span><br><span class="line">	ret = gettimeofday(&amp;nowTime, <span class="literal">NULL</span>);</span><br><span class="line">	<span class="keyword">if</span> (ret == <span class="number">-1</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		perror(<span class="string">&quot;gettimeofday error&quot;</span>);</span><br><span class="line">		<span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;nowTime: %lds+%ldus\n&quot;</span>, nowTime.tv_sec, nowTime.tv_usec);</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令编译程序：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall # 生成可执行文件 a.out </span><br><span class="line">./a.out # 执行可执行程序</span><br></pre></td></tr></table></figure><p>然后，终端会有以下信息显示：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">nowTime: 1655778991s+882392us</span><br></pre></td></tr></table></figure>
              </div>
            </details>

<h2 id="5-时间转换"><a href="#5-时间转换" class="headerlink" title="5. 时间转换"></a><font size=3>5. 时间转换</font></h2><p>上边两个函数可以获取到时间，但是呢，获取的都是相对于<code>1970-01-01 00:00:00 +0000 (UTC)</code>这个时间点所经过时间（日历时间），所以获取得到的是一个时间段的长度秒数，我们总不能真的自己去换算吧，<code>C</code>语言中已经为我们提供了相关函数来帮助我们做这个事情。</p>
<h3 id="5-1-ctime-函数"><a href="#5-1-ctime-函数" class="headerlink" title="5.1 ctime() 函数"></a><font size=3>5.1 ctime() 函数</font></h3><h4 id="5-1-1-函数说明"><a href="#5-1-1-函数说明" class="headerlink" title="5.1.1 函数说明"></a><font size=3>5.1.1 函数说明</font></h4><p>在<code>linux</code>下可以使用<code>man 3 ctime</code>命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;time.h&gt;</span></span></span><br><span class="line">    </span><br><span class="line"><span class="comment">/* 函数声明 */</span></span><br><span class="line"><span class="type">char</span> *<span class="title function_">ctime</span><span class="params">(<span class="type">const</span> <span class="type">time_t</span> *timep)</span>;</span><br><span class="line"><span class="type">char</span> *<span class="title function_">ctime_r</span><span class="params">(<span class="type">const</span> <span class="type">time_t</span> *timep, <span class="type">char</span> *buf)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数可以将日历时间转换为可打印输出的字符串形式，<code>ctime_r()</code>为<code>ctime()</code>函数的可重入版本，具体什么是可重入，什么是不可重入，现在就大概知道可重入版本的函数可以避免一些安全隐患，更加推荐使用。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li><code>timep</code>：<code>time_t</code>类型指针变量，该参数包含了一个日历时间，也就是上边获取时间函数获取的那个秒数。</li>
<li><code>buf</code>：<code>char</code>类型指针变量，该参数为可重入版本的函数<code>ctime()</code>所有，它指向存放转换后的时间字符串的缓冲区首地址。</li>
</ul>
<p><strong>【返回值】</strong><code>char</code>类型指针变量，成功则返回指向转换后得到的字符串；失败将返回<code>NULL</code>。</p>
<p><strong>【使用格式】</strong>一般情况下基本使用格式如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需要包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;time.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 至少应该有的语句 */</span></span><br><span class="line"><span class="type">char</span> tm_str[<span class="number">100</span>] = &#123;<span class="number">0</span>&#125;; </span><br><span class="line"><span class="type">time_t</span> tm;</span><br><span class="line">tm = time(<span class="literal">NULL</span>);</span><br><span class="line">ctime_r(&amp;tm, tm_str); <span class="comment">/* 一般使用可重入版本 */</span></span><br></pre></td></tr></table></figure>

<p><strong>【注意事项】</strong><code>none</code></p>
<h4 id="5-1-2-使用实例"><a href="#5-1-2-使用实例" class="headerlink" title="5.1.2 使用实例"></a><font size=3>5.1.2 使用实例</font></h4><details class="folding-tag" blue><summary> 点击查看实例 </summary>
              <div class='content'>
              <figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;time.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> arc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="type">char</span> tm_str[<span class="number">100</span>] = &#123;<span class="number">0</span>&#125;;</span><br><span class="line">	<span class="type">time_t</span> nowTime;</span><br><span class="line">	nowTime = time(<span class="literal">NULL</span>);</span><br><span class="line">	<span class="keyword">if</span> (nowTime == <span class="number">-1</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		perror(<span class="string">&quot;time error&quot;</span>);</span><br><span class="line">		<span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;nowTime: %lds\n&quot;</span>, nowTime);</span><br><span class="line">	ctime_r(&amp;nowTime, tm_str);</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;nowTime: %s\n&quot;</span>, tm_str);</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令编译程序：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall # 生成可执行文件 a.out </span><br><span class="line">./a.out # 执行可执行程序</span><br></pre></td></tr></table></figure><p>然后，终端会有以下信息显示：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">nowTime: 1655781498s</span><br><span class="line">nowTime: Tue Jun 21 11:18:18 2022</span><br></pre></td></tr></table></figure>
              </div>
            </details>

<h3 id="5-2-localtime-函数"><a href="#5-2-localtime-函数" class="headerlink" title="5.2 localtime() 函数"></a><font size=3>5.2 localtime() 函数</font></h3><h4 id="5-2-1-函数说明"><a href="#5-2-1-函数说明" class="headerlink" title="5.2.1 函数说明"></a><font size=3>5.2.1 函数说明</font></h4><p>在<code>linux</code>下可以使用<code>man 3 localtime</code>命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;time.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 函数声明 */</span></span><br><span class="line"><span class="keyword">struct</span> tm *<span class="title function_">localtime</span><span class="params">(<span class="type">const</span> <span class="type">time_t</span> *timep)</span>;</span><br><span class="line"><span class="keyword">struct</span> tm *<span class="title function_">localtime_r</span><span class="params">(<span class="type">const</span> <span class="type">time_t</span> *timep, <span class="keyword">struct</span> tm *result)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数可以把<code>time()</code>或<code>gettimeofday()</code>得到的秒数（<code>time_t</code>时间或日历时间）变成一个<code>struct tm</code>结构体所表示的时间，该时间对应的是本地时间。<code>localtime_r()</code>为<code>localtime()</code>函数的可重入版本，更加推荐使用。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li><code>timep</code>：<code>time_t</code>类型指针变量，该参数包含了一个日历时间，也就是上边获取时间函数获取的那个秒数。</li>
<li><code>result</code>：<code>struct tm</code>类型结构体指针变量，该参数为可重入版本的函数<code>localtime_r()</code>所有，转换后的本地时间将存放在该参数指向的结构体中。</li>
</ul>
<p><strong>【返回值】</strong><code>struct tm</code>类型的结构体指针，成功则返回一个有效的<code>struct tm</code>结构体指针，而对于可重入版本<code>localtime_r()</code>来说，成功执行情况下，返回值将会等于参数<code>result</code>；失败则返回<code>NULL</code>。</p>
<details class="folding-tag" blue><summary> 点击查看 struct tm 结构体成员 </summary>
              <div class='content'>
              <p>在使用<code>man</code>手册的时候，下边会有这个结构体成员的说明：</p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">tm</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">	<span class="type">int</span> tm_sec;    <span class="comment">/* 秒 Seconds (0-60) */</span></span><br><span class="line">	<span class="type">int</span> tm_min;    <span class="comment">/* 分 Minutes (0-59)*/</span></span><br><span class="line">	<span class="type">int</span> tm_hour;   <span class="comment">/* 时 Hours (0-23) */</span></span><br><span class="line">	<span class="type">int</span> tm_mday;   <span class="comment">/* 日 Day of the month (1-31) */</span></span><br><span class="line">	<span class="type">int</span> tm_mon;    <span class="comment">/* 月 Month (0-11) */</span></span><br><span class="line">	<span class="type">int</span> tm_year;   <span class="comment">/* 年 Year - 1900 */</span></span><br><span class="line">	<span class="type">int</span> tm_wday;   <span class="comment">/* 周 Day of the week (0-6, Sunday = 0) */</span></span><br><span class="line">	<span class="type">int</span> tm_yday;   <span class="comment">/* 一年中的第几天 Day in the year (0-365, 1 Jan = 0) */</span></span><br><span class="line">	<span class="type">int</span> tm_isdst;  <span class="comment">/* 夏令时 Daylight saving time */</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure><p>【注意事项】要想得到实际的时间，那么年份需要加上<code>1900</code>，月份需要加上<code>1</code>。这是因为这个函数内部转换的时候，年份从<code>1900</code>开始算，月份从<code>0</code>开始算了。</p>
              </div>
            </details>

<p><strong>【使用格式】</strong>一般情况下基本使用格式如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需要包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;time.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 至少应该有的语句 */</span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">tm</span> <span class="title">nowTime</span>;</span></span><br><span class="line"><span class="type">time_t</span> tm;</span><br><span class="line">tm = time(<span class="literal">NULL</span>);</span><br><span class="line">localtime_r(&amp;tm, &amp;nowTime);</span><br></pre></td></tr></table></figure>

<p><strong>【注意事项】</strong><code>none</code></p>
<h4 id="5-2-2-使用实例"><a href="#5-2-2-使用实例" class="headerlink" title="5.2.2 使用实例"></a><font size=3>5.2.2 使用实例</font></h4><details class="folding-tag" blue><summary> 点击查看实例 </summary>
              <div class='content'>
              <figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;time.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> arc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="class"><span class="keyword">struct</span> <span class="title">tm</span> <span class="title">nowTime</span>;</span></span><br><span class="line">	<span class="type">time_t</span> tm;</span><br><span class="line">	tm = time(<span class="literal">NULL</span>);</span><br><span class="line">	<span class="keyword">if</span> (tm == <span class="number">-1</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		perror(<span class="string">&quot;time error&quot;</span>);</span><br><span class="line">		<span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;tm: %lds\n&quot;</span>, tm);</span><br><span class="line">	localtime_r(&amp;tm, &amp;nowTime);</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;nowTime: %d年%d月%d日 %d:%d:%d\n&quot;</span>, </span><br><span class="line">			nowTime.tm_year + <span class="number">1900</span>, </span><br><span class="line">			nowTime.tm_mon + <span class="number">1</span>, </span><br><span class="line">			nowTime.tm_mday, </span><br><span class="line">			nowTime.tm_hour, </span><br><span class="line">			nowTime.tm_min, </span><br><span class="line">			nowTime.tm_sec);</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令编译程序：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall # 生成可执行文件 a.out </span><br><span class="line">./a.out # 执行可执行程序</span><br></pre></td></tr></table></figure><p>然后，终端会有以下信息显示：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">tm: 1655782709s</span><br><span class="line">nowTime: 2022年6月21日 11:38:29</span><br></pre></td></tr></table></figure>
              </div>
            </details>

<h2 id="6-时间相关API总结"><a href="#6-时间相关API总结" class="headerlink" title="6. 时间相关API总结"></a><font size=3>6. 时间相关<code>API</code>总结</font></h2><p>在<code>Linux</code>系统下常用的时间相关的系统调用和库函数，主要有下边几个：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">time_t</span> <span class="title function_">time</span><span class="params">(<span class="type">time_t</span> *tloc)</span>;</span><br><span class="line"><span class="type">int</span> <span class="title function_">stime</span><span class="params">(<span class="type">const</span> <span class="type">time_t</span> *t)</span>;</span><br><span class="line"><span class="type">char</span> *<span class="title function_">ctime</span><span class="params">(<span class="type">const</span> <span class="type">time_t</span> *timep)</span>;</span><br><span class="line"><span class="keyword">struct</span> tm *<span class="title function_">localtime</span><span class="params">(<span class="type">const</span> <span class="type">time_t</span> *timep)</span>;</span><br><span class="line"><span class="keyword">struct</span> tm *<span class="title function_">gmtime</span><span class="params">(<span class="type">const</span> <span class="type">time_t</span> *timep)</span>;</span><br><span class="line"><span class="type">time_t</span> <span class="title function_">mktime</span><span class="params">(<span class="keyword">struct</span> tm *tm)</span>;</span><br><span class="line"><span class="type">char</span> *<span class="title function_">asctime</span><span class="params">(<span class="type">const</span> <span class="keyword">struct</span> tm *tm)</span>;</span><br><span class="line"><span class="type">size_t</span> <span class="title function_">strftime</span><span class="params">(<span class="type">char</span> *s, <span class="type">size_t</span> max, <span class="type">const</span> <span class="type">char</span> *format, <span class="type">const</span> <span class="keyword">struct</span> tm *tm)</span>;</span><br><span class="line"><span class="type">char</span> *<span class="title function_">strptime</span><span class="params">(<span class="type">const</span> <span class="type">char</span> *s, <span class="type">const</span> <span class="type">char</span> *format, <span class="keyword">struct</span> tm *tm)</span>;</span><br><span class="line"><span class="type">int</span> <span class="title function_">gettimeofday</span><span class="params">(<span class="keyword">struct</span> timeval *tv, <span class="keyword">struct</span> timezone *tz)</span>;</span><br><span class="line"><span class="type">int</span> <span class="title function_">settimeofday</span><span class="params">(<span class="type">const</span> <span class="keyword">struct</span> timeval *tv, <span class="type">const</span> <span class="keyword">struct</span> timezone *tz)</span>;</span><br></pre></td></tr></table></figure>

<p>这些函数总结如下：</p>
<img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/LV05-07-Linux%E7%B3%BB%E7%BB%9F-02-%E7%B3%BB%E7%BB%9F%E6%97%B6%E9%97%B4/img/image-20220621120417357.png" alt="image-20220621120417357" style="zoom:50%;" />

<h1 id="三、进程时间"><a href="#三、进程时间" class="headerlink" title="三、进程时间"></a><font size=3>三、进程时间</font></h1><h2 id="1-什么是进程时间"><a href="#1-什么是进程时间" class="headerlink" title="1. 什么是进程时间"></a><font size=3>1. 什么是进程时间</font></h2><p>进程时间指的是进程从创建后（也就是程序运行后）到目前为止这段时间内使用<code>CPU</code>资源的时间总数，出于记录的目的，内核把<code>CPU</code>时间（进程时间）分为以下两个部分：</p>
<ul>
<li><p>用户<code>CPU</code>时间：进程在用户空间（用户态）下运行所花费的<code>CPU</code>时间，有时也称为虚拟时间（<code>virtual time</code>）。这对于程序来说，是它已经得到<code>CPU</code>的时间</p>
</li>
<li><p>系统<code>CPU</code>时间：进程在内核空间（内核态）下运行所花费的<code>CPU</code>时间。这是内核执行系统调用或代表进程执行的其它任务（例如，服务页错误）所花费的时间。</p>
</li>
</ul>
<p>一般来说，进程时间指的是用户<code>CPU</code>时间和系统<code>CPU</code>时间的总和，也就是总的<code>CPU</code>时间。</p>
<p>【注意事项】进程时间不等于程序的整个生命周期所消耗的时间，如果进程一直处于休眠状态（进程被挂起、不会得到系统调度），那么它并不会使用<code>CPU</code>资源，所以休眠的这段时间并不计算在进程时间中。</p>
<h2 id="2-times-函数"><a href="#2-times-函数" class="headerlink" title="2. times() 函数"></a><font size=3>2. times() 函数</font></h2><h3 id="2-1-函数说明"><a href="#2-1-函数说明" class="headerlink" title="2.1 函数说明"></a><font size=3>2.1 函数说明</font></h3><p>在<code>linux</code>下可以使用<code>man 2 times</code>命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/times.h&gt;</span></span></span><br><span class="line">    </span><br><span class="line"><span class="comment">/* 函数声明 */</span></span><br><span class="line"><span class="type">clock_t</span> <span class="title function_">times</span><span class="params">(<span class="keyword">struct</span> tms *buf)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数用于获取当前进程的时间。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li><code>buf</code>：<code>struct tms</code>类型接结构体指针变量，该参数指向一个保存了当前进程时间信息的<code>struct tms</code>结构体变量。</li>
</ul>
<details class="folding-tag" blue><summary> 点击查看 struct tms 结构体变量成员 </summary>
              <div class='content'>
              <p>在使用<code>man</code>手册的时候，会有该结构体的相关说明：</p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">tms</span></span></span><br><span class="line"><span class="class">&#123;</span></span><br><span class="line">	<span class="type">clock_t</span> tms_utime;  <span class="comment">/* user time */</span></span><br><span class="line">	<span class="type">clock_t</span> tms_stime;  <span class="comment">/* system time */</span></span><br><span class="line">	<span class="type">clock_t</span> tms_cutime; <span class="comment">/* user time of children */</span></span><br><span class="line">	<span class="type">clock_t</span> tms_cstime; <span class="comment">/* system time of children */</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure><p>上边的四个成员说明如下：</p><table>    <tr><td align="center" width=150px>tms_utime </td><td align="left">user time, 进程的用户CPU时间, tms_utime个系统节拍数</td></tr>    <tr><td align="center" width=150px>tms_stime </td><td align="left">system time, 进程的系统CPU时间, tms_stime个系统节拍数</td></tr>    <tr><td align="center" width=150px>tms_cutime</td><td align="left">user time of children, 已死掉子进程的tms_utime + tms_cutime时间总和</td></tr>    <tr><td align="center" width=150px>tms_cstime</td><td align="left">system time of children, 已死掉子进程的tms_stime + tms_cstime时间总和</td></tr></table>
              </div>
            </details>

<p><strong>【返回值】</strong><code>clock_t</code>类型（实质是<code>long</code>类型），成功时将返回从过去任意的一个时间点（例如系统启动时间）所经过的时钟滴答数（其实就是系统节拍数），将(节拍数 &#x2F; 节拍率)便可得到秒数，返回值可能会超过<code>clock_t</code>所能表示的范围（溢出）；调用失败返回<code>(clock_t) -1</code>，并设置<code>errno</code>表示错误类型。</p>
<p><strong>【使用格式】</strong>一般情况下基本使用格式如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需要包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/times.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 至少应该有的语句 */</span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">tms</span> <span class="title">t_buf_start</span>, <span class="title">t_buf_end</span>;</span> </span><br><span class="line"><span class="type">clock_t</span> t_start, t_end; </span><br><span class="line"><span class="type">long</span> tck;</span><br><span class="line">tck = sysconf(_SC_CLK_TCK);</span><br><span class="line">t_start = times(&amp;t_buf_start);</span><br><span class="line"><span class="comment">/* 要测试的语句块 */</span></span><br><span class="line">t_end = times(&amp;t_buf_end);</span><br></pre></td></tr></table></figure>

<p><strong>【注意事项】</strong><code>none</code></p>
<h3 id="2-2-使用实例"><a href="#2-2-使用实例" class="headerlink" title="2.2 使用实例"></a><font size=3>2.2 使用实例</font></h3><details class="folding-tag" blue><summary> 点击查看实例 </summary>
              <div class='content'>
              <figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/times.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> arc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="class"><span class="keyword">struct</span> <span class="title">tms</span> <span class="title">t_buf_start</span>;</span></span><br><span class="line">	<span class="class"><span class="keyword">struct</span> <span class="title">tms</span> <span class="title">t_buf_end</span>;</span></span><br><span class="line">	<span class="type">clock_t</span> t_start;</span><br><span class="line">	<span class="type">clock_t</span> t_end;</span><br><span class="line">	<span class="type">long</span> tck;</span><br><span class="line">	<span class="type">int</span> i, j;</span><br><span class="line">	<span class="comment">/* 获取系统的节拍率 */</span></span><br><span class="line">	tck = sysconf(_SC_CLK_TCK);</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;系统节拍率：%ld\n&quot;</span>, tck);</span><br><span class="line">	<span class="comment">/* 开始时间 */</span></span><br><span class="line">	t_start = times(&amp;t_buf_start);</span><br><span class="line">	<span class="keyword">if</span> (t_start == <span class="number">-1</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		perror(<span class="string">&quot;times error&quot;</span>);</span><br><span class="line">		<span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/* ------- 需要进行测试的代码段 ------- */</span></span><br><span class="line">	<span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; <span class="number">20000</span>; i++)</span><br><span class="line">		<span class="keyword">for</span> (j = <span class="number">0</span>; j &lt; <span class="number">20000</span>; j++);</span><br><span class="line">	<span class="comment">/* 休眠挂起 1s */</span></span><br><span class="line">	sleep(<span class="number">1</span>); </span><br><span class="line">	<span class="comment">/* --------------- end ---------------- */</span></span><br><span class="line">	<span class="comment">/* 结束时间 */</span></span><br><span class="line">	t_end = times(&amp;t_buf_end);</span><br><span class="line">	<span class="keyword">if</span> (t_end == <span class="number">-1</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		perror(<span class="string">&quot;times error&quot;</span>);</span><br><span class="line">		<span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">/* 打印时间 */</span></span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;时间总和: %f秒\n&quot;</span>, (t_end - t_start) / (<span class="type">double</span>)tck);</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;用户CPU时间: %f秒\n&quot;</span>, (t_buf_end.tms_utime - t_buf_start.tms_utime) / (<span class="type">double</span>)tck);</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;系统CPU时间: %f秒\n&quot;</span>, (t_buf_end.tms_stime - t_buf_start.tms_stime) / (<span class="type">double</span>)tck);</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令编译程序：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall # 生成可执行文件 a.out </span><br><span class="line">./a.out # 执行可执行程序</span><br></pre></td></tr></table></figure><p>然后，终端会有以下信息显示：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">系统节拍率：100</span><br><span class="line">时间总和: 1.180000秒</span><br><span class="line">用户CPU时间: 0.170000秒</span><br><span class="line">系统CPU时间: 0.000000秒</span><br></pre></td></tr></table></figure><p>可以看到用户<code>CPU</code>时间为<code>0.17</code>秒，系统<code>CPU</code>时间为<code>0</code>秒，也就是说测试的这段代码并没有进入内核态运行，所以</p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">总的进程时间 = 用户CPU时间 + 系统CPU时间 = <span class="number">0.17</span>秒</span><br></pre></td></tr></table></figure><p>上边显示的时间总和并不是总的进程时间，这个时间总和指的是从起点到终点所经过的时间，并不是进程时间。时间总和包括了进程处于休眠状态时消耗的时间（<code>sleep</code>等会让进程挂起、进入休眠状态），可以发现时间总和比进程时间多<code>1</code>秒，其实这一秒就是进程处于休眠状态的时间。至于还多出来了<code>0.01</code>秒，我自己感觉是语句执行耗费的时间，但也可能不是，这里我就没有追究那么深入了，后边万一用到了，搞明白了，再在这里补充修改吧。</p>
              </div>
            </details>

<h2 id="3-clock-函数"><a href="#3-clock-函数" class="headerlink" title="3. clock() 函数"></a><font size=3>3. clock() 函数</font></h2><h3 id="3-1-函数说明"><a href="#3-1-函数说明" class="headerlink" title="3.1 函数说明"></a><font size=3>3.1 函数说明</font></h3><p>在<code>linux</code>下可以使用<code>man 2 clock</code>命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;time.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 函数声明 */</span></span><br><span class="line"><span class="type">clock_t</span> <span class="title function_">clock</span><span class="params">(<span class="type">void</span>)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数也用于获取进程时间，使用方式比<code>times</code>更加简单。</p>
<p><strong>【函数参数】</strong><code>none</code></p>
<p><strong>【返回值】</strong><code>clock_t</code>类型，返回的值是到目前为止使用<code>CPU</code>的时间，这个时间并不是系统节拍数。要获得使用的秒数，还需要除以<code>CLOCKS_PER_SEC</code>。如果所用的处理器时间不可用，或者它的值无法表示，那么这个函数将返回值<code>(clock_t) -1</code>。</p>
<p><strong>【使用格式】</strong>一般情况下基本使用格式如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需要包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;time.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 至少应该有的语句 */</span></span><br><span class="line"><span class="type">clock_t</span> t_start, t_end;</span><br><span class="line">t_start = clock();</span><br><span class="line"><span class="comment">/* 测试的语句块 */</span></span><br><span class="line">t_end = clock();</span><br></pre></td></tr></table></figure>

<p><strong>【注意事项】</strong><code>clock()</code>函数虽然可以很方便的获取总的进程时间，但并不能获取到单独的用户<code>CPU</code>时间和系统<code>CPU</code>时间。</p>
<h3 id="3-2-使用实例"><a href="#3-2-使用实例" class="headerlink" title="3.2 使用实例"></a><font size=3>3.2 使用实例</font></h3><details class="folding-tag" blue><summary> 点击查看实例 </summary>
              <div class='content'>
              <figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;time.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> arc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line"></span><br><span class="line">	<span class="type">clock_t</span> t_start;</span><br><span class="line">	<span class="type">clock_t</span> t_end;</span><br><span class="line">	<span class="type">int</span> i, j;</span><br><span class="line">	<span class="comment">/* 开始时间 */</span></span><br><span class="line">	t_start = clock();</span><br><span class="line">	<span class="keyword">if</span> (t_start == <span class="number">-1</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		perror(<span class="string">&quot;clock error&quot;</span>);</span><br><span class="line">		<span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/* ------- 需要进行测试的代码段 ------- */</span></span><br><span class="line">	<span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; <span class="number">20000</span>; i++)</span><br><span class="line">		<span class="keyword">for</span> (j = <span class="number">0</span>; j &lt; <span class="number">20000</span>; j++);</span><br><span class="line">	<span class="comment">/* 休眠挂起 1s */</span></span><br><span class="line">	sleep(<span class="number">1</span>); </span><br><span class="line">	<span class="comment">/* --------------- end ---------------- */</span></span><br><span class="line">	<span class="comment">/* 结束时间 */</span></span><br><span class="line">	t_end = clock();</span><br><span class="line">	<span class="keyword">if</span> (t_end == <span class="number">-1</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		perror(<span class="string">&quot;clock error&quot;</span>);</span><br><span class="line">		<span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">/* 打印时间 */</span></span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;总CPU时间: %f秒, CLOCKS_PER_SEC = %ld\n&quot;</span>, (t_end - t_start) / (<span class="type">double</span>)CLOCKS_PER_SEC, CLOCKS_PER_SEC);</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令编译程序：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall # 生成可执行文件 a.out </span><br><span class="line">./a.out # 执行可执行程序</span><br></pre></td></tr></table></figure><p>然后，终端会有以下信息显示：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">总CPU时间: 0.197372秒, CLOCKS_PER_SEC = 1000000</span><br></pre></td></tr></table></figure>
              </div>
            </details>
    </div>

    
    
    

    <footer class="post-footer">




    <div>
        
            <div style="text-align:center;color: #ccc;font-size:14px;">
            ----------本文结束
            <i class="fas fa-fan fa-spin" style="color: #FF1493; font-size: 1rem"></i>
            感谢您的阅读----------
            </div>
        
    </div>





  
  <div class="my_post_copyright"> 
    <p><span>文章标题:</span><a href="/post/2bc2262c.html">LV05-07-Linux系统-02-系统时间</a></p>
    <p><span>文章作者:</span><a href="/" title="欢迎访问 《苏木》 的学习笔记">苏木</a></p>
    <p><span>发布时间:</span>2023年07月02日 - 21:52</p>
    <p><span>最后更新:</span>2025年06月14日 - 00:25</p>
    <p><span>原始链接:</span><a href="/post/2bc2262c.html" title="LV05-07-Linux系统-02-系统时间">https://sumumm.github.io/post/2bc2262c.html</a></p>
    <p><span>许可协议:</span><i class="fab fa-creative-commons"></i> <a rel="license" href= "https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
  </div>
  


          <div class="post-tags">
              <a href="/tags/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/" rel="tag"><i class="fa fa-tag"></i> LV05-操作系统</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/post/eef03213.html" rel="prev" title="LV05-07-Linux系统-03-随机数">
                  <i class="fa fa-angle-left"></i> LV05-07-Linux系统-03-随机数
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/post/a3406858.html" rel="next" title="LV05-07-Linux系统-01-系统信息获取">
                  LV05-07-Linux系统-01-系统信息获取 <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 2017 – 
    <span itemprop="copyrightYear">2025</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">苏木</span>
  </div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>站点总字数：</span>
    <span title="站点总字数">3.7m</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">225:26</span>
  </span>
</div>




    <span id="sitetime"></span>
    <script defer language=javascript>
        function siteTime()
        {
            window.setTimeout("siteTime()", 1000);
            var seconds = 1000;
            var minutes = seconds * 60;
            var hours = minutes * 60;
            var days = hours * 24;
            var years = days * 365;
            var today = new Date();
            var todayYear = today.getFullYear();
            var todayMonth = today.getMonth()+1;
            var todayDate = today.getDate();
            var todayHour = today.getHours();
            var todayMinute = today.getMinutes();
            var todaySecond = today.getSeconds();
            /*==================================================
            Date.UTC() -- 返回date对象距世界标准时间(UTC)1970年1月1日午夜之间的毫秒数(时间戳)
            year        - 作为date对象的年份，为4位年份值
            month       - 0-11之间的整数，做为date对象的月份
            day         - 1-31之间的整数，做为date对象的天数
            hours       - 0(午夜24点)-23之间的整数，做为date对象的小时数
            minutes     - 0-59之间的整数，做为date对象的分钟数
            seconds     - 0-59之间的整数，做为date对象的秒数
            microseconds - 0-999之间的整数，做为date对象的毫秒数
            ==================================================*/
            var t1 = Date.UTC(2017, 
                              5, 
                              19, 
                              0, 
                              0, 
                              0); //北京时间
            var t2 = Date.UTC(todayYear,todayMonth,todayDate,todayHour,todayMinute,todaySecond);
            var diff = t2-t1;
            var diffYears = Math.floor(diff/years);
            var diffDays = Math.floor((diff/days)-diffYears*365);
            var diffHours = Math.floor((diff-(diffYears*365+diffDays)*days)/hours);
            var diffMinutes = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours)/minutes);
            var diffSeconds = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours-diffMinutes*minutes)/seconds);
            document.getElementById("sitetime").innerHTML="已在这里 "+diffYears+" 年 "+diffDays+" 天 "+diffHours+" 小时 "+diffMinutes+" 分钟 "+diffSeconds+" 秒";
        }
        siteTime();
    </script>



    </div>
  </footer>

  
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/next-theme-pjax/0.6.0/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.28/fancybox/fancybox.umd.js" integrity="sha256-ytMJGN3toR+a84u7g7NuHm91VIR06Q41kMWDr2pq7Zo=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/lozad.js/1.16.0/lozad.min.js" integrity="sha256-mOFREFhqmHeQbXpK2lp4nA3qooVgACfh88fpJftLBbc=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.1/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>




  <script src="/js/third-party/fancybox.js"></script>

  <script src="/js/third-party/pace.js"></script>


  




  

  <script class="next-config" data-name="enableMath" type="application/json">true</script><script class="next-config" data-name="mathjax" type="application/json">{"enable":true,"tags":"none","js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-mml-chtml.js","integrity":"sha256-MASABpB4tYktI2Oitl4t+78w/lyA+D7b/s9GEP0JOGI="}}</script>
<script src="/js/third-party/math/mathjax.js"></script>


 
        <div id="click-show-text"
            data-mobile = false
            data-text = 富强,民主,文明,和谐,自由,平等,公正,法制,爱国,敬业,诚信,友善
            data-fontsize = 15px
            data-random= false>
        </div>
       

      
        <script async src=https://cdn.jsdelivr.net/npm/hexo-next-mouse-effect@latest/click/showText.js></script>
      

      
    




    <script async src="/js/fancybox_param.js"></script>





<!-- APlayer本体 -->



</body>
</html>
